package com.elitetyc.eliteim.server.handler;

import com.elitetyc.eliteim.common.constant.Constants;
import com.elitetyc.eliteim.common.handler.RequestMsgHandler;
import com.elitetyc.eliteim.common.proto.RequestProto;
import com.elitetyc.eliteim.server.config.IMServerProperties;
import com.elitetyc.eliteim.server.handler.impl.IMServerHeartBeatHandler;
import com.elitetyc.eliteim.server.holder.SessionSocketHolder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description 服务端统一消息处理器，根据消息的类型进行处理
 * 请查看 实现类
 * @see com.elitetyc.eliteim.common.handler.RequestMsgHandler
 * @Date 2021/9/16 10:30
 */
@SuppressWarnings({"unchecked","rawtypes"})
@Component
@Slf4j
@ChannelHandler.Sharable
public class ServerChannelHandler extends SimpleChannelInboundHandler<RequestProto.RequestProtocol> {

    @Autowired
    private List<RequestMsgHandler> requestMsgHandlers;

    @Autowired
    IMServerProperties imServerProperties;

    @Autowired
    private IMServerHeartBeatHandler imServerHeartBeatHandler;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RequestProto.RequestProtocol msg) throws Exception {
        if (msg.getType()!= Constants.RequestType.PING){
            log.info("receive msg {} ", msg.toString());
        }
        boolean handled = false;
        for (RequestMsgHandler msgHandler : requestMsgHandlers) {
            if (msgHandler.support(msg.getType())) {
                msgHandler.handleMsg(ctx, msg, msgHandler.convertProto2Msg(msg));
                handled = true;
            }
        }
        if (!handled) {
            log.warn("no handler handled msg");
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            final IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                // 外面添加了20秒没有接收到数据就会触发该方法
                imServerHeartBeatHandler.process(ctx);
            }
        }
        super.userEventTriggered(ctx, evt);
    }

    /**
     * 断开连接的时候,将用户channel移除
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SessionSocketHolder.removeSession((NioSocketChannel) ctx.channel());
    }

    /**
     * 异常时打印异常信息，并且移除通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        SessionSocketHolder.removeSession((NioSocketChannel) ctx.channel());
        log.error(cause.getMessage(),cause);
    }
}
